package com.lhs.Timer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lhs.entity.blog.blog_post;
import com.lhs.mapper.blog_post_0Mapper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.Temporal;
import java.util.List;

@Component
public class ArticlePublishScheduler {

    @Autowired
    private blog_post_0Mapper articleMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void scanAndPublish() {
        List<blog_post> articles = articleMapper.selectList(
                new QueryWrapper<blog_post>()
                        .eq("status", 2)
                        .between("publish_time",
                                LocalDateTime.now(),
                                LocalDateTime.now().plusHours(1)) // 未来1小时
        );

        for (blog_post article : articles) {
            long delay = Duration.between( LocalDateTime.now(),(Temporal) article.getPublishTime()).toMillis();
            if (delay <= 0) {
                // 已到时间，直接发布
                articleMapper.updateStatus(article.getId(), 1);
            } else {
                // 丢 MQ 短延时消息，保证准时发布
                rocketMQTemplate.syncSend(
                        "article_publish_topic",
                        MessageBuilder.withPayload(article.getId()).build(),
                        3000,
                        calculateDelayLevel(delay)
                );
            }
        }
    }

    private int calculateDelayLevel(long delay) {
        if (delay <= 1000) return 1;
        else if (delay <= 5000) return 2;
        else if (delay <= 10000) return 3;
        else if (delay <= 30000) return 4;
        else if (delay <= 60000) return 5;
        else if (delay <= 120000) return 6;
        else if (delay <= 300000) return 7;
        else if (delay <= 600000) return 8;
        else if (delay <= 1800000) return 9;
        else if (delay <= 3600000) return 10;
        else return 11;
    }
}
